package com.sudichina.sudichina.view.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.sudichina.sudichina.Contains;
import com.sudichina.sudichina.MyApp;
import com.sudichina.sudichina.NET.Api;
import com.sudichina.sudichina.NET.NetUtils;
import com.sudichina.sudichina.NET.onRequestDataFinish;
import com.sudichina.sudichina.R;
import com.sudichina.sudichina.adapter.BaseListViewViewHolder;
import com.sudichina.sudichina.adapter.MySuperListViewAdapter;
import com.sudichina.sudichina.bean.CarOrder;
import com.sudichina.sudichina.bean.Result;
import com.sudichina.sudichina.bean.TCarOwnOrderVO;
import com.sudichina.sudichina.bean.TConsignorOrderVO;
import com.sudichina.sudichina.entity.TSubmitOrderVO;
import com.sudichina.sudichina.utils.StringUtils;
import com.sudichina.sudichina.utils.Toastutils;
import com.sudichina.sudichina.view.activity.orlder.MyOrlderDetailActivity;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.sudichina.sudichina.R.id.tv_confim_older;
import static com.sudichina.sudichina.R.id.tv_size;
import static com.sudichina.sudichina.R.id.tv_state;

/**
 * Created by 杨伟乔 on 2016/11/23.
 * 邮箱:  yangweiqiao@126.com
 * CSDN: www.csdn.net/yangweiqiao
 * 神兽保佑,代码永无BUG
 */
@SuppressWarnings("unused")
public abstract class BaseFragemnt extends Fragment implements onRequestDataFinish {
    /**
     * 上下文
     **/
    protected Activity context;
    /**
     * 加载的布局 自定义的状态布局 里面包含四种加载的状态 成功 失败 空的 内容
     **/
    public StateLayout stateLayout;
    /**
     * fragment管理者
     **/
    public FragmentManager fragmentManager;
    /**
     * 里面涉及到fragment的嵌套 所以用到了子管理器
     **/
    public FragmentManager childFragmentManager;
    private List<CarOrder.ContentBean> contentBeanList;
    private MySuperListViewAdapter mySuperListViewAdapter;
    private List<CarOrder.ContentBean> newcontent;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //获取管理器
        fragmentManager = getFragmentManager();
        childFragmentManager = getChildFragmentManager();
        context = getActivity();
        // inflate方法返回值就是填充的布局的根控件
        // 填充出来的StateLayout已经包含了3种状态了
        stateLayout = (StateLayout) inflater.inflate(R.layout.state_layout, null);

        // 设置第4种状态：正常界面的状态。由于这里是Base类，Base类没有办法知道子View需要设置的正常界面是什么，所以正常界面的获取写成抽象方法由子类自己去实现。
        stateLayout.setContentView(getContentView());
//初始化控件
        initView();
        //初始化监听器
        initListener();
        //初始化数据
        initData();
        return stateLayout;
    }


    @Override
    public void onResume() {
        super.onResume();


    }

    /**
     * 增加这个方法是为了省略强转操作
     *
     * @param id 这个现在很少用到 都是黄油刀使用找控件
     * @return
     */
    public <T> T findView(int id) {
        @SuppressWarnings("unchecked")
        T view = (T) stateLayout.findViewById(id);
        return view;
    }

    /**
     * 根据服务器返回的数据判断要显示哪一个View
     * 方法的参数是list集合的类型
     *
     * @param datas
     * @return
     */
    public boolean checkDatas(Collection<?> datas) {
        boolean result = false;
        if (datas == null) {
            stateLayout.showFailView();
        } else if (datas.isEmpty()) {
            stateLayout.showEmptyView();
        } else {
            stateLayout.showContentView();
            result = true;
        }
        return result;
    }

    /**
     * 根据服务器返回的数据判断要显示哪一个View
     * 方法的参数是map集合类型
     *
     * @param datas
     * @return
     */
    public boolean checkDatas(Map<?, ?> datas) {
        boolean result = false;
        if (datas == null) {
            stateLayout.showFailView();
        } else if (datas.isEmpty()) {
            stateLayout.showEmptyView();
        } else {
            stateLayout.showContentView();
            result = true;
        }
        return result;
    }

    /**
     * 返回Fragment的标题名称
     */
    public abstract CharSequence getTitle();

    /**
     * 返回一个用于设置正常界面的View，可以是一个View，也可以是一个布局id
     */

    public Object getContentView() {
        return R.layout.listview;
    }

    public ListView listview_dingdan;

    /**
     * 初始化View的代码写在这个方法中
     */
    public void initView() {

        listview_dingdan = findView(R.id.listview_dingdan);
        // TODO: 2017/3/17 0017
        listview_dingdan.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(getActivity(), MyOrlderDetailActivity.class);
                intent.putExtra("older", newcontent.get(position));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
    }

    /**
     * 初始化监听器的代码写在这个方法中
     */
    public void initListener() {
    }

    ;

    /**
     * 初始化数据的代码写在这个方法中
     */
    public void initData() {

/**
 *
 Long id;
 Long consignorAccountId;
 Long vehOwnOrderId;
 String orderType;
 String tradeSubject;
 String orderDesc;
 String tradeStatus;
 Long userBillId;




 */


        requestdataolder();


        stateLayout.showLoadingView();


    }

    private void requestdataolder() {
        HashMap<String, Object> map = new HashMap<>();

        /*
        创建访问要解析的实体类
         */
        Type type = new TypeToken<Result<CarOrder>>() {
        }.getType();
        if (MyApp.getCurrentUser() != null) {

            map.put("tCarOwnAccountId", MyApp.getCurrentUser().getId());


            NetUtils.requestData(Api.LISTCARBYIT, map, this, type, false);

        }
    }


    /**
     * 定义一个任务的标记
     */
    protected final String HTTP_TASK_KEY = "HttpTaskKey_" + hashCode();


    /**
     * 获取任务标记
     *
     * @return
     */

    public String getHttpTaskKey() {
        return HTTP_TASK_KEY;
    }

    /**
     * 获取上下文
     *
     * @return
     */
    @Override
    public Context getContext() {
        return getActivity();
    }


    /**
     * 界面销毁的到时候取消任务
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }


    @Override
    public void requestdataFailed(IOException e) {
        stateLayout.showFailView();
        LinearLayout failView = (LinearLayout) stateLayout.findViewById(R.id.failView);
        failView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stateLayout.showLoadingView();
                initData();
            }
        });
    }


    @Override
    public void requestdataFinish(String catalog, Object bean) {
        switch (catalog) {
            case Api.UPDATETORDER:

                System.out.println("请求的结果是:" + bean);

                requestdataolder();


                break;


            case Api.LISTCARBYIT:
                //请求的订单的接口
                Result<CarOrder> carOrder = (Result<CarOrder>) bean;
                int code = carOrder.getCode();
                if (code == 1) {
                    //如果数据格式正确
                    //显示数据


                    CarOrder data = carOrder.getData();
                    if (data == null) {
                        stateLayout.showEmptyView();
                        return;
                    }


                    contentBeanList = data.getContent();
                    if (contentBeanList == null) {

                        stateLayout.showEmptyView();
                        return;
                    }


                    if (newcontent != null) {
                        newcontent.clear();
                        newcontent = setListData(contentBeanList);
                        if (mySuperListViewAdapter != null) {
                            mySuperListViewAdapter.notifyDataSetChanged();
                        }


                    } else {
                        newcontent = setListData(contentBeanList);
                    }


                    if (newcontent == null || newcontent.size() == 0) {
                        stateLayout.showEmptyView();
                        return;
                    }

                    mySuperListViewAdapter = new MySuperListViewAdapter(newcontent) {
                        @Override
                        public BaseListViewViewHolder setHolder() {


                            class myVIewHolder extends BaseListViewViewHolder {

                                @Override
                                public void setDatas(View view, Object obj, int position) {
                                    final CarOrder.ContentBean order = (CarOrder.ContentBean) obj;
                                    /*
                                    订单编号
                                     */
                                    TextView tv_ordernumber = (TextView) view.findViewById(R.id.tv_ordernumber);
                                    tv_ordernumber.setText(order.getOrderNo());
                                    /*
                                    订单状态
                                     */
                                    String tradeStatus = order.getTradeStatus();
                                    final String orderId = order.getId();
                                    System.out.println("订单的orderId是:" + orderId);
                                    TextView tvstate = (TextView) view.findViewById(tv_state);
                                    switch (tradeStatus) {

                                        case Contains.WEIFUKUAN:
                                            tvstate.setText("未付款");
                                            break;
                                        case Contains.HUOZHUDAISHOULI:
                                            tvstate.setText("待受理");
                                            break;

                                        case Contains.CHEZHUDAISHOULI:
                                            tvstate.setText("待受理");
                                            break;

                                        case Contains.YUECHEDAIQIANG:
                                            tvstate.setText("约车待抢");
                                            break;

                                        case Contains.DAIJIAOHUO:
                                            tvstate.setText("待交货");
                                            break;

                                        case Contains.DAITIHUO:
                                            tvstate.setText("待提货");
                                            break;

                                        case Contains.YUNSHUZHONG:
                                            tvstate.setText("运输中");
                                            break;
                                        case Contains.SONGDA:
                                            tvstate.setText("送达");
                                            break;
                                        case Contains.DAISHOUKUAN:
                                            tvstate.setText("待收款");
                                            break;
                                        case Contains.WANCHENG:
                                            tvstate.setText("完成");
                                            break;

                                    }


                                    /*
                                    订单价格
                                     */
                                    TextView tv_money = (TextView) view.findViewById(R.id.tv_money);
                                    tv_money.setText(order.getTotalMoney());
                                    /*
                                    订单出发地
                                     */
                                    TextView tv_adress_from = (TextView) view.findViewById(R.id.tv_adress_from);
                                    tv_adress_from.setText(order.getPickupAddress());
                                    /*
                                    订单目的地
                                     */
                                    TextView tv_adress_to = (TextView) view.findViewById(R.id.tv_adress_to);
                                    tv_adress_to.setText(order.getToZone());
                                    /*
                                    开始时间
                                     */
                                    TextView tv_begin_time = (TextView) view.findViewById(R.id.tv_begin_time);
                                    tv_begin_time.setText(StringUtils.formatDate(order.getTransStartTime()));
                                    /*
                                    结束时间
                                     */
                                    TextView tv_over_time = (TextView) view.findViewById(R.id.tv_over_time);
                                    tv_over_time.setText(StringUtils.formatDate(order.getTransEndTime()));
                                    /*
                                    货物类型
                                     */
                                    TextView tv_categoty = (TextView) view.findViewById(R.id.tv_categoty);
                                    tv_categoty.setText(order.getItemName());
                                    /*
                                    货物大小
                                     */
                                    //货物的大小这里 可以是斤 方 吨 判断哪个里面有值
                                    TextView tvsize = (TextView) view.findViewById(tv_size);
                                    String weight = order.getWeight();
                                    String volume = order.getVolume();
                                    if (weight != null) {
                                        tvsize.setText(weight + "吨");
                                    } else if (volume != null) {
                                        tvsize.setText(volume + "方");
                                    }


                                    /*
                                    按钮 1 取消位置的按钮
                                     */
                                    TextView tv_cancle_older = (TextView) view.findViewById(R.id.tv_cancle_older);
                                    // TODO: 2017/3/22 根据订单的状态来显示这里的内容
  /*
                                    确定位置的按钮
                                     */
                                    TextView tvconfim_older = (TextView) view.findViewById(tv_confim_older);


                                    String tradeStatus1 = order.getTradeStatus();
                                    switch (tradeStatus1) {

                                        case Contains.WEIFUKUAN:

                                        case Contains.HUOZHUDAISHOULI:

                                        case Contains.CHEZHUDAISHOULI:
                                        case Contains.YUECHEDAIQIANG:

                                            //可以取消订单
                                            tv_cancle_older.setVisibility(View.GONE);


                                            tvconfim_older.setText("取消订单");


                                            break;
                                        case Contains.DAIJIAOHUO:
                                            tv_cancle_older.setVisibility(View.VISIBLE);
                                            tv_cancle_older.setText("取消订单");
                                            tv_cancle_older.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    //取消订单
                                                    Toastutils.showToast("取消订单");
                                                }
                                            });
break;
                                        case Contains.DAITIHUO:
                                            //可以取消订单
                                            tv_cancle_older.setVisibility(View.VISIBLE);
                                            tv_cancle_older.setText("取消订单");
                                            tv_cancle_older.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    //取消订单
                                                    Toastutils.showToast("取消订单");
                                                }
                                            });

                                            tvconfim_older.setText("确认揽货");

                                            tvconfim_older.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    //确认揽货
                                                    //改变状态为把状态变为运输中
                                                    confim(orderId, Contains.YUNSHUZHONG);


                                                }
                                            });

                                            break;


                                        case Contains.YUNSHUZHONG:
//只有确认按钮tv_cancle_older
                                            tv_cancle_older.setVisibility(View.GONE);
                                            tvconfim_older.setText("确认送达");
                                            tvconfim_older.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    //确认送达
                                                    confim(orderId, Contains.SONGDA);

                                                }
                                            });
                                            break;
//                                        case Contains.SONGDA://有确认收货 和申诉的按钮
//                                            tv_cancle_older.setVisibility(View.VISIBLE);
//                                            tv_cancle_older.setText("申诉");
//                                            tv_cancle_older.setOnClickListener(new View.OnClickListener() {
//                                                @Override
//                                                public void onClick(View v) {
//                                                    //申诉
//                                                }
//                                            });
//                                            tvconfim_older.setText("确认收货");
//                                            tvconfim_older.setOnClickListener(new View.OnClickListener() {
//                                                @Override
//                                                public void onClick(View v) {
//                                                    //确认收货
//                                                    confim(orderId, Contains.DAISHOUKUAN);
//                                                }
//                                            });
//
//                                            break;
                                        case Contains.DAISHOUKUAN:
                                            tv_cancle_older.setVisibility(View.VISIBLE);
                                            tv_cancle_older.setText("申诉");
                                            tv_cancle_older.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    //申诉
                                                }
                                            });
                                            tvconfim_older.setText("确认收款");
                                            tvconfim_older.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    //确认收货
                                                    confim(orderId, Contains.WANCHENG);
                                                }
                                            });
                                            break;

                                        case Contains.WANCHENG:
                                            //只有申诉的订单
                                            tv_cancle_older.setVisibility(View.GONE);

                                            tvconfim_older.setText("申诉");
                                            tvconfim_older.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    //申诉
                                                    Toastutils.showToast("申诉电话: 13021029600");
                                                }
                                            });
                                            break;
                                    }


                                }

                                @Override
                                public int getItemId() {
                                    return R.layout.item_listview_dingdan;
                                }
                            }
                            return new myVIewHolder();


                        }
                    };

                    listview_dingdan.setAdapter(mySuperListViewAdapter);


                }
                stateLayout.showContentView();

                break;


        }


        System.out.println("数据是:" + bean);
        System.out.println("成功");


    }

    private void confim(String id, String status) {
//services/submitOrder/updateTOrder


        TSubmitOrderVO entity = new TSubmitOrderVO();
        TCarOwnOrderVO carOrderVo = new TCarOwnOrderVO();
        TConsignorOrderVO consignorOrderVo = new TConsignorOrderVO();
        consignorOrderVo.setId(id);
        consignorOrderVo.setTradeStatus(status);
        entity.settCarOrderVo(null);
        entity.settConsignorOrderVo(consignorOrderVo);
        entity.settOrderItemVo(null);

        //NetUtils.requestData(Api.ROBTORDER, map, this, null, false);
        NetUtils.requestDataformentity(Api.UPDATETORDER, entity, this, null);


    }

    protected abstract List<CarOrder.ContentBean> setListData(List<CarOrder.ContentBean> content);


}
